﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Dao.PlcDao;
using DeHeng_Mes.Model;
using DeHeng_Mes.Model.Boss;
using DeHeng_Mes.Model.BossModel;
using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.PlcModel;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Service.Plc;
using DeHeng_Mes.Thread;
using DeHeng_Mes.Utils;
using FluentFTP;
using NPOI.SS.Formula.Functions;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using yingli_ningbo.Helpers;
using static DeHeng_Mes.Utils.Tools;
using MappingTable = DeHeng_Mes.Utils.MappingTable;
using RichTextBox = System.Windows.Forms.RichTextBox;
using SqlSugar;
using Org.BouncyCastle.Tls;
using System.Windows.Input;
using System.IO;
using DeHeng_Mes.Service;
using System.Linq;
using System.Xml.Linq;
using DeHeng_Mes.Model.OrderSingleton;

namespace DeHeng_Mes.Business
{
    public partial class MainForm : Form
    {

        #region 全局成员
        private PlcConnectionManager _plcConnectionManager;
        private FactoryMes factoryMesThread;
        private PlcCollectionData plcCollectionData = new PlcCollectionData();
        PlcServicees PlcService = new PlcServicees();
        MesDataPush dataPush = new MesDataPush();
        PowerGather powerGather = new PowerGather();
        ErrorGather errorGather = new ErrorGather();
        #endregion

        public MainForm()
        {
            InitializeComponent();

            FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
        }

        /// <summary>
        /// 私有转换公有
        /// </summary>
        public RichTextBox ProductionLogsText
        {
            get => ProductionLogs;

            set => ProductionLogs = value;
        }

        /// <summary>
        /// 私有转换公有
        /// </summary>
        public RichTextBox DeviceLogsText
        {
            get => DeviceLogs;

            set => DeviceLogs = value;
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 在这里执行需要的任务
            DialogResult result = MessageBox.Show("确定要关闭吗？", "确认", MessageBoxButtons.YesNo);

            // 如果用户点击了 No，则取消关闭
            if (result == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                // 读取当日最终耗电量与产量
                PlcService.GetPowerAndProdution(false);
            }
        }

        /// <summary>
        /// 窗体首次加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryInfo_LoadAsync(object sender, EventArgs e)
        {
            factoryMesThread = new FactoryMes();

            ToolControl(this);

            List<PlcConfigModel> plcList = InitPlcConfig();

            if (plcList != null && plcList.Count > 0)
            {
                _plcConnectionManager = new PlcConnectionManager(plcList);
            }

            // 检测数据库连接
            bool isCollect = SqlConnect();

            // plc连接线程
            _plcConnectionManager.ConnectToPlc();

            // 检测线体Plc是否存在未完成订单
            _ = factoryMesThread.OrderIsOk();

            // 启动Plc交互采集线程
            _ = plcCollectionData.CollectionTask();

            // 启动0点监控线程
            //_ = PlcService.Timer();

            // 启动工厂数据推送线程
            Task.Run(() =>
            {
                _ = dataPush.pushTask();
            });

            // 启动压铆数据采集线程
            Task.Run(async () => { await PlcService.ReadCSVData(); });

            // 启动拉铆数据采集线程
            Task.Run(async () => { await PlcService.ReadRiveteData(); });

            // PLC时间同步
            //_ = PlcService.TimeToPlc();

            // 启动工厂Mes线程监听订单信息
            _ = factoryMesThread.GetOrderDetails();

            //启动报警线程
            Task.Run(() => { _ = errorGather.GetError(); });

            // 启动推送明暗码线程
            Task.Run(async () =>
            {
                await dataPush.CodePushTask();
            });
        }

        #region 自定义方法

        /// <summary>
        /// 初始化PLC配置
        /// </summary>
        private List<PlcConfigModel> InitPlcConfig()
        {
            string[] ips = new string[] { "192.168.7.1" };
            string[] names = new string[] { "P6" };
            string[] nicks = new string[] { "W04-SUB" };
            List<PlcConfigModel> plcConfigs = new List<PlcConfigModel>();
            for (int i = 0; i < ips.Length; i++)
            {
                PlcConfigModel plcConfigModel = new PlcConfigModel();
                plcConfigModel.plc = new Plc(CpuType.S71500, ips[i], 0, 1);
                plcConfigModel.nick = nicks[i];
                plcConfigModel.name = names[i];
                plcConfigModel.cpu = CpuType.S71500;
                plcConfigModel.ip = ips[i];
                plcConfigModel.rack = 0;
                plcConfigModel.slot = 1;
                plcConfigModel.heartBeat = 5000;
                plcConfigModel.retryInterval = 3000;
                plcConfigModel.readInterval = 10000;
                plcConfigModel.isConnected = false;
                plcConfigs.Add(plcConfigModel);
            }
            return plcConfigs;
        }

        #endregion
    }
}
